import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link ,browserHistory} from 'react-router';
import request from 'superagent';
import $ from 'jquery';
import api from '../api';
import {bind_change} from '../common/State';

import {  Modal,Icon,message,Table,Dropdown,Menu,Row,Col,Button,Input,InputNumber,Form ,Select,Switch,Upload} from 'antd';
import NavBar from '../common/NavBar';
import Alert from '../common/Alert';
import ContentBody from '../common/ContentBody';
const Option = Select.Option;
const InputGroup = Input.Group;

//导入常量
import cities from '../constants/cities';
import {ROLE_TYPE} from '../constants/index';

class StaffEdit extends React.Component {
  constructor(props, context){
      super(props, context);
      this.state={
          staff:{},
          visible:false,
          dutyList:[],
          departmentList:[],
          areaList:[],
          managerList:[]
      };
  }

  componentWillMount(){
    let {id} = this.props.location.query||{};
    this.doGet(id)
  }

  componentDidMount(){

  }

  async doGet(id){
    var {
      staffResult,
      dutyResult,
      departmentResult,
      areaResult,
      managerResult
    } = await api('/authority/staff/get',{id});

    let staff = {},
        dutyList = [],
        departmentList = [],
        areaList = [],
        managerList = [] ;

    if(staffResult.cd==0){
      staff = staffResult.data;
    }
    if(dutyResult.cd==0){
      dutyList = dutyResult.data;
    }
    if(departmentResult.cd==0){
      departmentList = departmentResult.data;
    }
    if(areaResult.cd==0){
      areaList = areaResult.data;
    }
    if(managerResult.cd==0){
      managerList = managerResult.data
    }
    this.setState({
      staff,
      dutyList,
      departmentList,
      areaList,
      managerList
    });
  }

  //保存事件
  btnSaveClick(event){
      const {validateFieldsAndScroll } = this.props.form;
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          return
        }
        this.save(values)
      })
  }
  //保存请求
  async save(values){
    let {staff} = this.state;
    values.roleName = ROLE_TYPE[values.roleNumber];
    values.isActive = values.isActive==true?1:0;
    values = Object.assign({},staff,values);
    var result = await api(`/authority/staff/save`,values)
      if(result.cd != 0){
        message.error(result.msg);
      }else{
        message.success("保存成功！" ,2,()=>{
           browserHistory.push({pathname:`/authority/staff/list`})
        });
      }
  }

  //弹窗保存
  async modalSave(values,resetFields){
    let {renderType} = this.state;

    let modalType = {
        duty:{
          url:'/authority/save/duty'
        },
        area:{
          url:'/authority/save/area'
        },
        department:{
          url:'/authority/save/department'
        }
    }
    let curObj = modalType[renderType];
    let {addResult,result} = await api(curObj.url,{...values});
    if(addResult.cd!=0){
      message.error(addResult.msg);
      return
    }
    resetFields();
    this.setState({
      visible:false,
      [[renderType]+'List']:result.data||[]
    })
  }

  //changeSelect
  changeSelect(value,e){
     const { getFieldDecorator,setFieldsValue} = this.props.form;
    if(value=='add'){
    }
    setFieldsValue({'duty':'jack'});
  }

  render() {
    const { getFieldDecorator,setFieldsValue} = this.props.form;
    var {
      staff,
      renderType,
      dutyList,
      departmentList,
      areaList,
      managerList
    } = this.state;
    return (
        <div>
            <NavBar navs={[
              {title:'员工列表',href:'/authority/staff/list'},
              {title:'创建新员工'}
            ]} />
            <ContentBody className='container'>
                <h2>员工基本信息</h2>
                <div className='height20'></div>
                <form>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="员工编号"
                          >
                            {getFieldDecorator('number', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入员工编号',
                                },
                              ],
                              initialValue:staff.number||""
                            })(<InputNumber
                                  style={{width:'100%'}}
                                  formatter = {(value) => {
                                    value = value.toString();
                                    if(value.length > 11){
                                      return value.slice(0,11)
                                    }
                                    return value
                                  }}
                                  placeholder="请输入员工编号"
                                />
                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item
                            label="员工姓名"
                          >
                            {getFieldDecorator('name', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入员工姓名',
                                },
                              ],
                              initialValue:staff.name||""
                            })(<Input size="large"  placeholder="请输入员工姓名" />)}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="手机号码"
                          >
                            {getFieldDecorator('phone', {
                              rules: [
                                {
                                  required: true,
                                  len:11,
                                  message: '请输入手机号码',
                                },
                              ],
                              initialValue:staff.phone||""
                            })(<Input type='number'  style={{width:'100%'}}    placeholder="请输入手机号码" />)}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item
                            label="电子邮箱"
                          >
                            {getFieldDecorator('email', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入电子邮箱',
                                },
                              ],
                              initialValue:staff.email||""
                            })(<Input size="large"  placeholder="请输入电子邮箱" />)}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="担任职务"
                          >
                            {getFieldDecorator('duty', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择担任职务',
                                },
                              ],
                              initialValue:staff.duty?staff.duty.toString():""
                            })(
                                <Select
                                  showSearch
                                  style={{ width: '100%' }}
                                  placeholder='请选择担任职务'
                                >
                                   <Option value="">请选择</Option>
                                  {dutyList.map((item,index)=>{
                                    return (
                                      <Option key={index} value={item.name}>{item.name}</Option>
                                    )
                                  })}
                                  <Option disabled  value="add" style={{textAlign:'center'}}>
                                    <Button
                                      style={{width:'100%',borderWidth:'0'}}
                                      onClick={(e)=>{
                                        e.target.focus();
                                        e.stopPropagation();
                                        this.setState({
                                          visible:true,
                                          renderType:'duty'
                                        })
                                      }}
                                    >+添加</Button>
                                  </Option>
                                </Select>

                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item
                            label="所在部门"
                          >
                            {getFieldDecorator('department', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入所在部门',
                                },
                              ],
                              initialValue:staff.department?staff.department.toString():""
                            })(
                              <Select
                                showSearch
                                style={{ width: '100%' }}
                                placeholder='请选择所在部门'
                              >
                                <Option value="">请选择</Option>
                                {departmentList.map((item,index)=>{
                                  return (
                                    <Option key={index} value={item.name}>{item.name}</Option>
                                  )
                                })}
                                <Option disabled  value="add" style={{textAlign:'center'}}>
                                  <Button
                                    style={{width:'100%',borderWidth:'0'}}
                                    onClick={(e)=>{
                                      e.stopPropagation();
                                      this.setState({
                                        visible:true,
                                        renderType:'department'
                                      })
                                    }}
                                  >+添加</Button>
                                </Option>
                              </Select>
                            )}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="所在区域"
                          >
                            {getFieldDecorator('area', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入所在区域',
                                },
                              ],
                              initialValue:staff.area?staff.area.toString():""
                            })(
                              <Select
                                  showSearch
                                  style={{ width: '100%' }}
                                  placeholder='请选择所在区域'
                                >
                                   <Option value="">请选择</Option>
                                  {areaList.map((item,index)=>{
                                    return (
                                      <Option key={index} value={item.name}>{item.name}</Option>
                                    )
                                  })}
                                  <Option disabled  value="add" style={{textAlign:'center'}}>
                                    <Button
                                      style={{width:'100%',borderWidth:'0'}}
                                      onClick={(e)=>{
                                        e.stopPropagation();
                                        this.setState({
                                          visible:true,
                                          renderType:'area'
                                        })
                                      }}
                                    >+添加</Button>
                                  </Option>
                                </Select>
                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item
                            label="所在城市"
                          >
                            {getFieldDecorator('city', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入所在城市',
                                },
                              ],
                              initialValue:staff.city?staff.city.toString():""
                            })(
                              <Select
                                  showSearch
                                  style={{ width: '100%' }}
                                  placeholder='请选择所在城市'
                                  filterOption={(input, option) => {
                                    if(!option.props['data-label']) return;
                                     return option.props['data-label'].toLowerCase().indexOf(input.toLowerCase()) >= 0
                                  }}
                                >
                                  <Option value="">请选择</Option>
                                  {cities.map((item,index)=>{
                                    return (
                                      <Option key={index} data-label={item.label} value={item.name}>{item.name}</Option>
                                    )
                                  })}
                              </Select>
                            )}
                          </Form.Item>
                      </Col >
                    </Row>
                </form>
                <h2>员工权限设置</h2>
                <div className='height20'></div>
                <form>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="角色类型"
                          >
                            {getFieldDecorator('roleNumber', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择角色类型',
                                },
                              ],
                              initialValue:staff.roleNumber?staff.roleNumber+"":""
                            })(
                              <Select
                                  style={{ width: '100%' }}
                                  placeholder='请选择角色类型'
                                  onChange={(value)=>{
                                    staff.roleNumber = value;
                                    this.setState({
                                      staff
                                    })
                                  }}
                                >
                                  <Option value="">请选择</Option>
                                  {Object.keys(ROLE_TYPE).map((key,index)=>{
                                    return (
                                      <Option key={index} value={key.toString()}>{ROLE_TYPE[key]}</Option>
                                    )
                                  })}
                              </Select>
                            )}
                          </Form.Item>
                      </Col >
                      {staff.roleNumber==4?
                        <Col span={12}>
                            <Form.Item
                              label="归属业务经理"
                            >
                              {getFieldDecorator('manager', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请输入归属业务经理',
                                  },
                                ],
                                initialValue:staff.manager?staff.manager.toString():""
                              })(
                                <Select
                                  style={{ width: '100%' }}
                                >
                                  <Option value="">请选择</Option>
                                  {managerList.map((item,index)=>{

                                    return (
                                      <Option key={index} value={item.id.toString()}>{item.name}</Option>
                                    )
                                  })}
                              </Select>
                              )}
                            </Form.Item>
                        </Col >
                        :null
                      }


                    </Row>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item
                            label="是否在职"
                            style={{display:'flex'}}
                          >
                            {getFieldDecorator('isActive', {
                              valuePropName: 'checked',
                              initialValue: staff.isActive==1?true:staff.isActive==0?false:true,
                            })(<Switch
                              checkedChildren="在职"
                              unCheckedChildren="离职"
                            />)}
                          </Form.Item>
                      </Col >
                    </Row>
                </form>
                <div className="text-center ">
                    <Button
                      type='primary'
                      onClick={this.btnSaveClick.bind(this)}
                    >
                      保存
                    </Button>
                    <Button
                        type='default'
                        style={{marginLeft:"20px"}}
                        onClick={()=>{this.context.router.push('/authority/staff/list')}}
                      >
                        返回
                      </Button>
                 </div>
            </ContentBody>

            <ModalInfoForm
              visible={this.state.visible}
              onClose={()=>{this.setState({visible:false})}}
              onOk={this.modalSave.bind(this)}
              renderType={renderType}
            />

        </div>
    );
  }
}
StaffEdit.contextTypes= { router: React.PropTypes.object.isRequired};

class ModalInfo extends React.Component {
  constructor(props, context){
    super(props, context);
    this.state={
    };
  }

  componentWillMount(){

  }

  componentDidMount(){

  }
  validateFiled(){
    let {onOk} = this.props;
    const { resetFields } = this.props.form;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        onOk(values,resetFields);
      }
    });
  }
  //添加职务弹出内容
  renderDutyHtml(){
    const { getFieldDecorator } = this.props.form;
    return (
        <Form>
          <Row>
            <Col span={24}>
              <Form.Item
                label="职务名称"
              >
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入职务名称',
                    },
                  ],
                })(<Input size="large"  placeholder="请输入职务名称" />)}
              </Form.Item>
            </Col >
          </Row>
        </Form>
    )
  }

  //添加部门弹出内容
  renderDepartmentHtml(){
    const { getFieldDecorator} = this.props.form;
    return (
        <Form>
          <Row>
            <Col span={24}>
              <Form.Item
                label="部门名称"
              >
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入部门名称',
                    },
                  ],
                })(<Input size="large"  placeholder="请输入部门名称" />)}
              </Form.Item>
            </Col >
          </Row>
        </Form>
    )
  }

  //添加区域弹出内容
  renderAreaHtml(){
    const { getFieldDecorator} = this.props.form;
    return (
        <Form>
          <Row>
            <Col span={24}>
              <Form.Item
                label="区域名称"
              >
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入区域名称',
                    },
                  ],
                })(<Input size="large"  placeholder="请输入区域名称" />)}
              </Form.Item>
              </Col >
          </Row>
        </Form>
    )
  }

  render () {
    const { getFieldDecorator} = this.props.form;
    let {visible,onClose,onOk,renderType} = this.props;
    return (
      <Modal
          title={renderType=='duty'?'添加职务'
                  :renderType=='area'?'添加区域'
                  :renderType=='department'?'添加部门'
                  :'提示'
                }
          visible={visible}
          onOk={this.validateFiled.bind(this)}
          onCancel={onClose}
          style={{
            zIndex:'1999'
          }}
        >
          {renderType=='duty'?
            this.renderDutyHtml()
            :renderType=='area'?
            this.renderAreaHtml()
            :renderType=='department'?
            this.renderDepartmentHtml()
            :null
          }
        </Modal>
    )
  }
}

var ModalInfoForm = Form.create()(ModalInfo);
export default Form.create()(StaffEdit);
